﻿/**************************************************
*                      Main
**************************************************/
$(function () {

    // Declare global configurations
    $.configGlobal = {
        // Uri api fields
        uriGetMotelsAPI: "http://localhost:1790/motelmaps/all_address",
        urtGetWardsAPI: "http://localhost:1790/motelmaps/all_wards/{0}",
        urtGetDistrictsAPI: "http://localhost:1790/motelmaps/all_districts",
        urlGetResultSearchAPI: "http://localhost:1790/motelmaps/re_search/{0}/{1}",
        urlDeleteMotelsAPI: "http://localhost:1790/motelmaps/delete_address/{0}",
        // Protocol call
        protoGET: "GET",
        protoPOST: "POST",
        protoDELETE: "DELETE",
        protoPUT: "PUT",
        // Expected datatype
        dataJSON: "json",
        // ContentType
        ctnJSON: "application/json; charset=utf-8",
        // Html fields
        divContainMap: "map_canvas",
        cbWardSearch: "#cbWardSearchAddress",
        cbWardAdd: "#cbWardAddress",
        cbDistrictSearch: "#cbDistrictSearchAddress",
        cbDistrictAdd: "#cbDistrictAddress",
        btnSearch: "#btnsearch",
        btnSave: "#btnSave",
        btnCancel: "#btnCancel",
        msgAddResponse: "#msgAddAddress",
        btnShowAllMotels: "#btnShow",
        // Variabel fields
        infoWindow: new google.maps.InfoWindow(),
        menuContext: "",
        currentPointer: "",
        visibleStatus: 1,
        disableStatus: 0,
        mapDiv: "",
        mapObject: "",
        defaultLocaltion: [10.7633174, 106.6823476],
        defaultZoom: 13,
        defaultScaleControl: true,
        districts: "",
        wardsSearch: "",
        wardsAdd: "",
        motels: "",
        addsSearch: ""
    };

    var $map = $('#map_canvas'),
         menu = new Menu($map),
         currentPointer;

    // Menu item 01
    menu.add('Submenu 01', 'itemB',
            function () {
                menu.close();
                addMarker(false);
            });

    // Menu item 02
    menu.add('Submenu 02', 'itemA separator',
            function () {
                menu.close();
                addMarker(true);
            });

    $.configGlobal.mapObject = $map;
    $.configGlobal.menuContext = menu;
    $.configGlobal.currentPointer = currentPointer;

    // Load Districts ComboBox
    getDistrictsComboBoxes();

    // Load default map
    RetrievePlaces();

    // Add selected index changing to 
    $($.configGlobal.cbDistrictAdd).change(cbDistrictAddSelectedIndexChanging);
    $($.configGlobal.cbDistrictSearch).change(cbDistrictSearchSelectedIndexChanging);

});

function cbDistrictAddSelectedIndexChanging() {
    var selectedDistrict = $($.configGlobal.cbDistrictAdd).val();
    // Call ajax to motel api
    $.ajax({
        url: $.configGlobal.urtGetWardsAPI.format(selectedDistrict),
        type: $.configGlobal.protoGET,
        dataType: $.configGlobal.dataJSON,
        contentType: $.configGlobal.ctnJSON,
        success: function (data) {
            if (data == null) {
                console.log("returned data from ward add api is empty !");
                return;
            }
            // Assign list motels to global
            $.configGlobal.wardsAdd = data;
            console.log("call ward add api success");
            // Binding comboBoxes
            loadWardsToAddComboBox();
        },
        error: function (request, status, msg) {
            console.log(msg);
        }
    });
}

function cbDistrictSearchSelectedIndexChanging() {
    var selectedDistrict = $($.configGlobal.cbDistrictSearch).val();
    // Call ajax to motel api
    $.ajax({
        url: $.configGlobal.urtGetWardsAPI.format(selectedDistrict),
        type: $.configGlobal.protoGET,
        dataType: $.configGlobal.dataJSON,
        contentType: $.configGlobal.ctnJSON,
        success: function (data) {
            if (data == null) {
                console.log("returned data from ward search api is empty !");
                return;
            }
            // Assign list motels to global
            $.configGlobal.wardsSearch = data;
            console.log("call ward search api success");
            // Binding comboBoxes
            loadWardsToSearchComboBox();
        },
        error: function (request, status, msg) {
            console.log(msg);
        }
    });
}

// Declare function to binding ward to combobox add form
function getDistrictsComboBoxes() {
    // Call ajax to motel api
    $.ajax({
        url: $.configGlobal.urtGetDistrictsAPI,
        type: $.configGlobal.protoGET,
        dataType: $.configGlobal.dataJSON,
        contentType: $.configGlobal.ctnJSON,
        success: function (data) {
            if (data == null) {
                console.log("returned data from districts api is empty !");
                return;
            }
            // Assign list motels to global
            $.configGlobal.districts = data;
            console.log("call districts api success");
            // Binding comboBoxes
            var tempDistricts = $.configGlobal.districts;
            // Check type of motels global is none array
            if (!(tempDistricts instanceof Array)) {
                console.log("districts variable none array types");
                return;
            }
            console.log("districts variable is array types");
            var tempSizeOfDistricts = tempDistricts.length;
            if (tempSizeOfDistricts < 1) {
                console.log("districts variable is empty");
                return;
            }
            console.log("length of districts is {0}".format(tempSizeOfDistricts));
            // Get combobox  add form
            var tempDistrictAddCombo = $($.configGlobal.cbDistrictAdd);
            var tempDistrictSearchCombo = $($.configGlobal.cbDistrictSearch);
            // Each item in ward 
            for (var i = 0; i < tempSizeOfDistricts; i++) {
                var tempDistrict = tempDistricts[i];
                tempDistrictAddCombo.append("<option value='{0}'>{1}</option>".format(tempDistrict.MaQuan, tempDistrict.TenQuan));
                tempDistrictSearchCombo.append("<option value='{0}'>{1}</option>".format(tempDistrict.MaQuan, tempDistrict.TenQuan));
                tempDistrict = null;
            }
        },
        error: function (request, status, msg) {
            console.log(msg);
        }
    });
}

// Retrieve places
function RetrievePlaces() {
    // Call ajax to motel api
    $.ajax({
        url: $.configGlobal.uriGetMotelsAPI,
        type: $.configGlobal.protoGET,
        dataType: $.configGlobal.dataJSON,
        contentType: $.configGlobal.ctnJSON,
        success: function (data) {
            if (data == null) {
                console.log("returned data from motel api is empty !");
                return;
            }
            // Assign list motels to global
            $.configGlobal.motels = data;
            console.log("call motel api success");
            // Generate map
            LoadMaps();
        },
        error: function (msg, url, line) {
            console.log(msg);
        }
    });
}

// Function to load map
function LoadMaps() {
    var $map = $.configGlobal.mapObject,
    menu = new Menu($map),
    center = $.configGlobal.defaultLocaltion;
    var tempMotels = $.configGlobal.motels;
    // Check type of motels global is none array
    if (!(tempMotels instanceof Array)) {
        console.log("motels variable none array types");
        return;
    }
    console.log("motels variable is array types");
    var tempSizeOfMotels = tempMotels.length;
    if (tempSizeOfMotels < 1) {
        console.log("motels variable is empty");
        return;
    }
    var arrayResult = [];
    // Each item in temp array motel
    for (var i = 0; i < tempSizeOfMotels; i++) {
        var tempLocation = tempMotels[i];
        var contentInfoWindow = $('.info').html();
        var test = tempLocation.SoNha + " " + tempLocation.TenDuong;
        contentInfoWindow = contentInfoWindow.format(test, tempLocation.KinhDo,
                                                                                   tempLocation.ViDo, tempLocation.MaDiaChi,
                                                                                   tempLocation.MaDiaChi);
        var itemMarker = { lat: tempLocation.KinhDo, lng: tempLocation.ViDo, data: contentInfoWindow };
        arrayResult.push(itemMarker);
        tempLocation = null;
    }

    $map.gmap3(
            {// Declare init function
                action: 'init',
                options: { center: center, zoom: 15 },
                events: {
                    rightclick: function (map, event) {
                        currentPointer = event;
                        menu.open(currentPointer);
                    },
                    click: function () {
                        menu.close();
                    },
                    dragstart: function () {
                        menu.close();
                    },
                    zoom_changed: function () {
                        menu.close();
                    }
                }
            },
            {
                action: 'addMarkers',
                markers: arrayResult,
                events: {
                    mouseover: function (marker, event, data) {
                        var map = $(this).gmap3('get'),
                            infowindow = $(this).gmap3({ action: 'get', name: 'infowindow' });
                        if (infowindow) {
                            infowindow.open(map, marker);
                            infowindow.setContent(data);
                        } else {
                            $(this).gmap3({ action: 'addinfowindow', anchor: marker, options: { content: data} });
                        }
                    },
                    mouseout: function () {
                        var infowindow = $(this).gmap3({ action: 'get', name: 'infowindow' });
                        if (infowindow) {
                            infowindow.close();
                        }
                    }
                }
            }
     );
}